package com.base.base

import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.viewpager.widget.PagerAdapter
import java.lang.IllegalStateException

/**
 * fragment 适配器
 * @param manager
 * @param fragments 需要加载的fragment集
 * @param titles 所有fragment标题集 如果获取不到标题会从fragment中直接获取
 *
 */
open class IFragmentAdapter(val manager: FragmentManager, var fragments: List<Fragment>, var titles: List<CharSequence>): PagerAdapter() {
    private var transaction: FragmentTransaction? = null// 操作Fragment对象
    private var currentFragment: Fragment ?= null // 当前窗口显示的Fragment
    private val tagMap by lazy { mutableMapOf<Fragment,String>() }
    constructor(manager: FragmentManager): this(manager, arrayListOf(), arrayListOf())
    constructor(manager: FragmentManager, fragments: List<Fragment>): this(manager,fragments, arrayListOf())
    init { init() }

    /**
     * 初始化填充用来标记Fragment的参数
     */
    private fun init(){
        val map = mutableMapOf<Fragment,String>()
        for (fragment in fragments){
            map[fragment] = tagMap[fragment] ?: randomAll(10)
        }
        tagMap.clear()
        tagMap.putAll(map)
    }

    /**
     * 刷新时调用初始化方法 更新标记
     */
    override fun notifyDataSetChanged() {
        init()
        super.notifyDataSetChanged()
    }

    /**
     * 开始更新Fragment
     */
    override fun startUpdate(container: ViewGroup) {
        if(container.id == View.NO_ID) throw IllegalStateException("ViewGroup 没有设置ID")
        transaction = manager.beginTransaction()
    }

    /**
     * 结束更新Fragment
     */
    override fun finishUpdate(container: ViewGroup) {
        transaction?.commitAllowingStateLoss()
    }

    /**
     * 获取Item数量
     */
    override fun getCount(): Int {
        return fragments.size
    }

    /**
     * 该视图是否是Fragment中的视图
     */
    override fun isViewFromObject(view: View, any: Any): Boolean {
        return (any as? Fragment)?.view == view
    }

    /**
     * 获取需要加载到窗口的Fragment
     */
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val tag = tagMap[fragments[position]]
        var fragment = manager.findFragmentByTag(tag)

        if(fragment == null){
            fragment = fragments[position]
            transaction?.add(container.id,fragment,tag)
        }

        return fragment
    }

    /**
     * 设置当前显示Item
     */
    override fun setPrimaryItem(container: ViewGroup, position: Int, any: Any) {
        if(any != currentFragment){
            currentFragment?.setMenuVisibility(false)
            currentFragment = any as? Fragment
        }

        currentFragment?.setMenuVisibility(true)
        transaction?.show(currentFragment ?: return)
    }

    /**
     * 销毁Item
     */
    override fun destroyItem(container: ViewGroup, position: Int, any: Any) {
        if (any !is Fragment) return
        any.setMenuVisibility(false)
        when{
            fragments.contains(any) -> transaction?.hide(any)
            else -> {
                transaction?.remove(any)
                tagMap.remove(any)
                deleteItem(any)
            }
        }
    }

    open fun deleteItem(fragment: Fragment){}

    /**
     * 获取Fragment title
     */
    override fun getPageTitle(position: Int): CharSequence? {
        return titles.getOrNull(position)
    }


}